package com.xiaohu.gen;

import com.xiaohu.entity.Table;
import com.xiaohu.mapper.ColumnsMapper;
import com.xiaohu.mapper.TableMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.xiaohu.gen.VelocityUtils.*;

/**
 * 自动生成代码工具类
 */
// @RestController
@Slf4j
@RestController
public class XGenCodeUtils {

    private String url = "jdbc:mysql://139.224.212.99:3306/destiny?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true";

    @Autowired
    private TableMapper tableMapper;


    @Autowired
    private ColumnsMapper columnsMapper;

    /**
     * 生成表结构
     *
     * @param tableName 要生成代码的表名
     * @return Zip压缩包
     */
    @PostMapping("rl")
    public void buildCode(@RequestParam("tableName") String tableName) throws IOException {
        String schema = url.substring(0, url.indexOf('?')).substring(url.lastIndexOf('/') + 1);
        // 获取表元素
        Table tableData = tableMapper.getTableData(schema, tableName);
        tableData.setTableName(humpTransition(tableData.getTableName()));
        tableData.setPackagePath("com.yupi.springbootinit");
        // 获取表结构
        tableData.setColumnsList(propertyTransition(columnsMapper.getColumnsList(schema, tableName)));
        // 初始化
        VelocityUtils.initVelocity();
        // 设置模板
        List<String> templates = VelocityUtils.initVelocityTemplate();
        // 数据填充
        VelocityContext velocityContext = getVelocityContext(tableData);
        // 创建一个临时文件，用于存储ZIP文件
        File outputFile;
        outputFile = new File(getDesktopPath(), "XGenCode.zip");
        try (ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(outputFile.toPath()))) {
            for (String template : templates) {
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, "UTF-8");
                tpl.merge(velocityContext, sw);
                // 将字符串写入ZIP条目
                ZipEntry zipEntry = new ZipEntry(getFileName(template, tableData));
                zipOut.putNextEntry(zipEntry);
                zipOut.write(sw.toString().getBytes(StandardCharsets.UTF_8));
                zipOut.closeEntry();
            }
            log.info("生成文件路径: " + outputFile.getAbsolutePath());
        } catch (IOException e) {
            log.error("渲染模板失败，表名：" + e);
            throw e;
        }
    }
}

